(function(window){
    var Z = {};

    Z.ajax = function(o){
	var success = o.success || function(){};
	o.type = o.type || "GET";
	o.dataType = o.dataType || "json";
	o.cache = o.cache || false;
	o.success = function(rsp,status,xhr){
	    if(rsp == null){
		Z.alert('服务器端错误');
		return;
	    }
	    switch(rsp.status){
		case 'XT001':
		    if(rsp.msg != ''){
			Z.tip(rsp.msg,1);
		    }
		    success(rsp.data);
		    break;
		case 'XT002':
		    Z.alert(rsp.msg||'操作失败');
		    break;
		case 'XT003':
		    Z.alert(rsp.msg||'您不具备此操作权限');
		    break;
		case 'XT004':
		    Z.alert(rsp.msg||'请先<a href="'+Z.url('/backend/auth/login',true)+'">登录</a>');
		    break;
		default:
		    Z.alert('未知错误!');
		    break;
	    }
	};
	o.error = o.error || (function(jqXHR,status,errorThrown){
	    Z.log(status.toString());
	});
	$.ajax(o);
    };

    /**
     * parameters = {
     *              url: http://www.test.com,
     *              templates: {
     *                          list: "",                       返回数据列表的模板
     *                          none: "",                       当返回数据为空是要显示的模板
     *                          methods:{}                   模板函数
     *                          }
     *              containers:{
     *                          list: "",                       显示返回数据容器的ID
     *                          pageLinks  : ""                 显示分页链接容器的ID
     *                      },
     *               data:{
     *                      type: 1                             ajax请求时要传递的参数
     *                  },
     *               after: function(){}                        请求成功之后
     *              }
     */
    Z.AjaxFill = function(parameters){
	$.extend(this,parameters);
	this.data = this.data||{};
	this.data.page = this.data.page || 1;
	this.data.pageSize = this.data.pageSize || 10;
	this.after = this.after || function(){};
	this.loading = null;
	return this;
    };

    Z.AjaxFill.prototype = {
	request : function(data){
	    this.loading = Z.loading(this.containers.loading);
	    var _this = this;
	    $.extend(this.data,data||{});
	    Z.ajax({
		url    : this.url,
		data   : this.data,
		success: function(data){
		    _this.success(data);
		},
		error  : this.error
	    });
	},
	success : function(data){
	    this.loading.hide();
	    if(typeof data.total == 'undefined'){
		this._rendList(data);
	    }else{
		if(data.total > 0){
		    if(data.records.length > 0 && this.data.page > 0){
			this._rendList(data.records);
			this._rendPageLinks(data.total);
		    }else{
			this.prev();
		    }
		}else{
		    $(this.containers.pageLinks).hide();
		    $(this.containers.list).html(this.templates.none||'');
		}
	    }
	    this.after(data);
	},
	error : function(jqXHR,status,errorThrown){
	    Z.log('服务器端错误，请检查远程服务器web服务是否启动。');
	},
	setParameter : function(p,v){
	    this[p] = v;
	    return this;
	},
	go : function(page){
	    this.request({
		page : page
	    });
	},

	next : function(){
	    this.request({
		page : ++this.data.page
	    });
	},

	prev : function(){
	    this.request({
		page: --this.data.page
	    });
	},

	reload : function(flag){
	    this.go(flag?1:this.data.page);
	},

	_rendList : function(records){
	    if(typeof this.templates.list == 'string'){
		$.template("listTemplate",this.templates.list);
		$(this.containers.list).html($.tmpl("listTemplate",records,(this.templates.methods||{}))).fadeIn(200);
	    }else{
		$(this.containers.list).html('').append($(this.templates.list).tmpl(records,this.templates.methods||{})).fadeIn(200);
	    }
	},

	_rendPageLinks : function(total){
	    var _this = this;
	    if(this.data.pageSize < total){
		var pageLinks = Z.AjaxFill.generatePageLinks(total,this.data.pageSize,this.data.page);
		$(this.containers.pageLinks).html(pageLinks).show();

		$(this.containers.pageLinks).find("a").click(function(){
		    _this.go(Z.parseInt($(this).attr("page")));
		    return false;
		});

		$(this.containers.pageLinks).find("li.pages-select>select").change(function(){
		    _this.go(Z.parseInt($(this).val()));
		});
	    }else{
		$(this.containers.pageLinks).hide();
	    }
	}
    };

    Z.AjaxFill.parseTemplate = function(template,object,flag){
	return template.replace(/\${(\w+?)}/g,function(){
	    return object[arguments[1]]!=undefined?object[arguments[1]]:(flag==undefined?arguments[0]:flag);
	}).replace(/@{(\w+?)}/g, function(){
	    return window[arguments[1]]!=undefined?window[arguments[1]]:(flag==undefined?arguments[0]:flag);
	});
    };

    Z.AjaxFill.generatePageLinks = function(total,pageSize,page){
	var i,totalPage = Math.ceil(total/pageSize),
	pageLinks = ['<ul class="pagination"><li class="info">'+page+'/'+totalPage+' </li>'];

	if(page==1){
	    pageLinks.push('<li title="«" class="previous active">上一页</li>');
	}else{
	    pageLinks.push('<li class="previous"><a title="«" href="javascript:void(0);" page="'+(page-1)+'">上一页</a></li>');
	}

	if(totalPage > 10){
	    if(page > 7&&page < (totalPage-6)){
		pageLinks.push('<li><a href="javascript:void(0);" page="1">1</a></li>');
		pageLinks.push('<li>...</li>');
		for(i=(page-5);i<(page+6);i++){
		    if(i==page){
			pageLinks.push('<li class="active">'+i+'</li>');
		    }else{
			pageLinks.push('<li><a href="javascript:void(0);" page="'+i+'">'+i+'</a></li>');
		    }
		}
		pageLinks.push('<li>...</li>');
		pageLinks.push('<li><a href="javascript:void(0);" page="'+(totalPage)+'">'+(totalPage)+'</a></li>');
	    }else if(page <= 7){
		for(i=1;i<11;i++){
		    if(i==page){
			pageLinks.push('<li class="active">'+i+'</li>');
		    }else{
			pageLinks.push('<li><a href="javascript:void(0);" page="'+i+'">'+i+'</a></li>');
		    }
		}
		pageLinks.push('<li>...</li>');
		pageLinks.push('<li><a href="javascript:void(0);" page="'+totalPage+'">'+totalPage+'</a></li>');
	    }else{
		pageLinks.push('<li><a href="javascript:void(0);" page="1">1</a></li>');
		pageLinks.push('<li>...</li>');

		for(i=(totalPage-9);i<=totalPage;i++){
		    if(i==page){
			pageLinks.push('<li class="active">'+i+'</li>');
		    }else{
			pageLinks.push('<li><a href="javascript:void(0);" page="'+i+'">'+i+'</a></li>');
		    }
		}
	    }
	}else{
	    for(i=1;i<totalPage+1;i++){
		if(i==page){
		    pageLinks.push('<li class="active">'+i+'</li>');
		}else{
		    pageLinks.push('<li><a href="javascript:void(0);" page="'+i+'">'+i+'</a></li>');
		}
	    }
	}

	if(page==totalPage){
	    pageLinks.push('<li class="next active">下一页</li>');
	}else{
	    pageLinks.push('<li class="next"><a  title="»" href="javascript:void(0);" page="'+(parseInt(page)+1)+'">下一页</a></li>');
	}

	pageLinks.push('<li class="pages-select"><select name="pages">');
	for(i=totalPage;i>0;i--){
	    pageLinks.push('<option value="'+i+'"'+(i==page?'selected="selected"':'')+'>'+i+'</option>');
	}
	pageLinks.push('</select></li></ul>');

	return pageLinks.join("");
    };

    /*   Dialog Start   */
    Z.Dialog = function(parameter){
	var o = (typeof parameter == "string")?{
	    content:parameter
	}:parameter;

	this.id = 'z-dialog-'+(new Date()).valueOf();

	this.ui = '<div class="z-dialog" id="'+this.id+'">\
                       <div class="z-dialog-background"></div>\
                       <div class="z-dialog-content"></div>\
                   </div>';

	$('body').append(this.ui);

	switch(typeof o.content){
	    case 'string':
		$(this.find('.z-dialog-content')).html(o.content);
		break;
	    case 'object':
		$(this.find('.z-dialog-content')).append(o.content);
		break;
	}

	$(this.find('.z-dialog-background')).css({
	    "opacity":(o.opacity||"0.6"),
	    "background-color":(o.bgColor||"#000000")
	});

	$(this.find('.z-dialog-content')).width(o.width || 300);

	var _this = this;

	$(document).keypress(function(e){
	    if(e.keyCode == 27){
		_this.close(parameter.close || function(){});
	    }
	});

	$(this.find('.z-dialog-background')).click(function(){
	    _this.close(parameter.close || function(){});
	});
    };

    Z.Dialog.prototype.open = function(f){
	$('#'+this.id).show();
	(f || function(){})(this);
	this.alignCenter();
    };

    Z.Dialog.prototype.close = function(f){
	(f||function(){})(this);
	$('#'+this.id).remove();
    };

    Z.Dialog.prototype.alignCenter = function(){
	$(this.find('.z-dialog-content')).css({
	    "margin-left":-($(this.find('.z-dialog-content')).width()/2)+"px",
	    "margin-top":-($(this.find('.z-dialog-content')).height()/2)+"px"
	});
    };

    Z.Dialog.prototype.find = function(selector){
	return $('#'+this.id).find(selector);
    };

    /**
     * o = {
     *      title: "",
     *      content: "",
     *      width: "",
     *      onOpen: function(){},
     *      onClose: function(){}
     *      }
     **/
    Z.alert = function(parameter){
	var o = (typeof parameter == "string")?{
	    content:parameter
	}:parameter;

	var ui = '<div class="z-alert">\
                    <div class="z-header">\
                        <div class="z-title">'+(o.title||'')+'</div>\
                        <a class="z-close" href="javascript:void(0);">X</a>\
                    </div>\
                    <div class="z-content"></div>\
                  </div>';

	var dialog = new Z.Dialog({
	    content:ui,
	    width: o.width || 300
	});

	dialog.open(function(){
	    if(typeof o.conent == 'string'){
		$(dialog.find('.z-content')).html(o.content);
	    }else{
		$(dialog.find('.z-content')).append(o.content);
	    }

	    $(dialog.find('a.z-close')).click(function(){
		dialog.close(o.onClose||function(){});
	    });


	    (o.onOpen||function(){})(dialog);
	});

	return dialog;
    };

    Z.confirm = function(parameter){
	var o = (typeof parameter == "string")?{
	    content:parameter
	}:parameter;

	var ui = '<div class="z-confirm">\
                    <div class="z-header">\
                        <div class="z-title">'+(o.title||'')+'</div>\
                        <a class="z-close">close </a>\
                    </div>\
                    <div class="z-content"></div>\
                    <div class="z-bottom" style="padding:10px 0;background-color:#ffffff;overflow:auto;">\
                        <a class="z-confirm" href="javascript:void(0);" style="display:inline-block;width:80px;text-align:center;height:20px;line-height:20px;float:left;margin-left:20px;">确定</a>\
                        <a class="z-cancel" href="javascript:void(0);" class="cancel" style="display:inline-block;width:80px;text-align:center;height:20px;line-height:20px;float:right;margin-right:20px;">取消</a><div class="clear"></div>\
                    </div>\
                  </div>';

	var dialog = new Z.Dialog(ui);

	dialog.open(function(){
	    if(typeof o.conent == 'string'){
		$(dialog.find('.z-content')).html(o.content);
	    }else{
		$(dialog.find('.z-content')).append(o.content);
	    }

	    $(dialog.find('a.z-confirm')).click(function(){
		dialog.close(o.onConfirm||function(){});
	    });

	    $(dialog.find('a.z-cancel')).click(function(){
		dialog.close(o.onCancel||function(){});
	    });

	    $(dialog.find('a.z-close')).click(function(){
		dialog.close(o.onClose||function(){});
	    });

	    $(document).keypress(function(e){
		if(e.keyCode == 13){
		    $(dialog.find('a.z-confirm')).trigger('click');
		}
	    });

	    (o.onOpen||function(){})(dialog);
	});

	return dialog;
    };

    Z.loading = function(target){
	var ui = $(target).find('div.z-loading');
	if(ui.length > 0){
	    ui.show();
	}else{
	    ui = $('<div class="z-loading"><img src="'+Z.url('/assets/img/z-ajax-loading.gif')+'"/></div>');
	    $(target||'body').append(ui);
	}
	return ui;
    };

    Z.tip = function(content,seconds){
	var dialog = new Z.Dialog({
	    content: '<div class="dialog-tip" style="width:300px;background-color:#ffffff;border:5px solid #f0f0f0;padding:15px;text-align:center;">'+content+'</div>',
	    opacity: '0.4'
	});
	dialog.open();
	var timeout = window.setTimeout(function(){
	    dialog.close();
	    window.clearTimeout(timeout);
	}, seconds*1000);
    };

    Z.form = function(o){
	var onOpen = o.onOpen || function(){};
	o.onOpen = function(dialog){
	    onOpen(dialog);
	    dialog.find("form").submit(function(){
		(o.onSubmit||function(){})(dialog);
		Z.ajax({
		    type:$(this).attr("method"),
		    url: $(this).attr("action"),
		    data: $(this).serializeArray(),
		    success: function(d){
			(o.success||function(d){})(d);
			dialog.close();
		    }
		});
		return false;
	    });
	};
	return Z.alert(o);
    };


    Z.LightBox = function(thumbs,getSource,getDescription,func){
	var _this = this,
	moreImage = Z.url('/assets/img/more'+((LANG||'')=='en'?'-en':'')+'.jpg'),
	closeImage = Z.url('/assets/img/close.jpg'),
	fs = func ||{
	    open:function(){},
	    close: function(){}
	};

	this.init = false;
	this.ui = '\
                    <div class="z-light-box">\
                        <div class="z-image-container"></div>\
                        <div class="z-description">\
                            <div class="z-background"></div>\
                            <div class="z-content"></div>\
                        </div>\
                        <a href="javascript:void(0);" class="z-prev"></a>\
                        <a href="javascript:void(0);" class="z-next"></a>\
                        <a href="javascript:void(0);" class="z-more">\
			    <img src="'+moreImage+'" alt="more"/>\
			</a>\
                        <a href="javascript:void(0);" class="z-close">\
			    <img src="'+closeImage+'" alt="close"/>\
			</a>\
                    </div>';
	this.thumbs = $(thumbs);
	this.getSource = getSource || function(thumb){
	    return $(thumb).find('img').attr('src').replace(/_thumb\.(jpg|jpeg|gif|bmp|png)$/,'.$1');
	};
	this.getDescription = getDescription || function(thumb){
	    return $(thumb).attr('title');
	};
	this.index = 0;
	this.length = $(thumbs).length;

	this.dialog = null;
	this.loading = null;


	$(thumbs).each(function(index){
	    $(this).live('click',function(){
		var scrollBox = null;
		_this.index = index;
		if(!_this.init){
		    _this.dialog = new Z.Dialog({
			content:_this.ui,
			close: fs.close
		    });
		    _this.dialog.open(function(){
			fs.open();

			if(_this.length >1 ){
			    _this.dialog.find('a.z-next').addClass('active');
			}

			_this.go(_this.index);

			_this.dialog.find('.z-description .z-content').html(_this.getDescription($(this)));

			_this.dialog.find('.z-description').hide();

			_this.dialog.find('.z-prev').click(function(){
			    _this.prev();
			    $(this).trigger('blur');
			});
			_this.dialog.find('.z-next').click(function(){
			    _this.next();
			    $(this).trigger('blur');
			});

			_this.dialog.find('.z-close').click(function(){
			    _this.dialog.close(fs.close);
			});

			_this.dialog.find('.z-more').click(function(){
			    _this.dialog.find('.z-description .z-background').css('opacity',0.8);
			    _this.dialog.find('.z-description').toggle();
			    if(_this.dialog.find('.z-description:visible').length > 0){
				if(scrollBox == null){
				    scrollBox = new Z.ScrollBox({
					target: _this.dialog.find('.z-description .z-content'),
					height: _this.dialog.find('.z-description').height()*0.9,
					verticalBlockHeight: 40,
					position : {
					    top:0
					}
				    });
				}else{
				    scrollBox.init({
					targetWidth  : _this.dialog.find('.z-description .z-content').width(),
					height       : _this.dialog.find('.z-description').height() * 0.9
				    });
				}
			    }
			});
		    });
		}else{
		    _this.go(_this.index);
		}
	    })
	});
    };

    Z.LightBox.prototype.go = function(){
	var _this = this,
	src = this.getSource(this.thumbs.eq(this.index)),
	other = $.browser.msie?'onabort="this.src=this.src;"':'';
	if(this.init){
	    this.dialog.find('.z-light-box .z-image-container img').fadeOut(200,function(){
		$(this).html('');
	    });
	}
	_this.dialog.find('.z-description').hide();
	this.loading = Z.loading(this.dialog.find('.z-light-box'));

	this.dialog.find('.z-image-container').html('<img src="'+src+'" alt="" style="display:none;" '+other+'/>');
	this.dialog.find('.z-image-container img').load(function(){
	    _this.animate(Z.LightBox.calculateSize($(this)));
	});

	if(this.index <= 0){
	    this.dialog.find('.z-prev').removeClass('active');
	    this.dialog.find('.z-next').not('.active').addClass('active');
	}else if(this.index >= this.length -1){
	    this.dialog.find('.z-next').removeClass('active');
	    this.dialog.find('.z-prev').not('.active').addClass('active');
	}else{
	    this.dialog.find('.z-prev').not('.active').addClass('active');
	    this.dialog.find('.z-next').not('.active').addClass('active');
	}
    };

    Z.LightBox.prototype.next = function(){
	//this.index = (this.index >= this.length - 1)?0:(this.index + 1);

	if(this.index < this.length - 1){
	    this.index++;
	    this.go();
	}
    };

    Z.LightBox.prototype.prev = function(){
	//this.index = (this.index <= 0)?(this.length-1):(this.index-1);

	if(this.index > 0){
	    this.index--;
	    this.go();
	}
    };

    Z.LightBox.prototype.animate = function(size){
	this.dialog.find('.z-image-container img').css({
	    'height':size.height+'px',
	    'width':size.width+'px'
	});

	this.dialog.find('.z-light-box').show().animate({
	    'width':size.width+'px',
	    'margin-left':-size.width/2+'px'
	},300,function(){
	    $(this).animate({
		'height': size.height+'px',
		'margin-top':-size.height/2+'px'
	    }, 250, function(){
		$(this).find('.z-loading').fadeOut(250);
		$(this).find('.z-image-container img').show();
	    })
	});
    };

    Z.LightBox.calculateSize = function(image){
	var imageWidth = $(image).width(), imageHeight = $(image).height(),
	windowWidth = $(window).width(), windowHeight = $(window).height(),
	w = imageWidth, h = imageHeight;

	if(imageWidth > windowWidth){
	    w = windowWidth * 0.8;
	    h = w * imageHeight / imageWidth;
	}
	if(imageHeight > windowHeight){
	    h = windowHeight * 0.8;
	    w = h * imageWidth / imageHeight;
	}
	return {
	    width:w,
	    height:h
	};
    };
    /* Dialog End */

    //Z ScrollBox
    Z.ScrollBox = function(o){
	$.extend(this,o);
	this.offset = {
	    top:0,
	    left:0
	};
	this.build();
    };

    Z.ScrollBox.prototype = {
	build: function(){
	    this.targetHeight = this.target.height();
	    this.targetWidth = this.target.width();
	    this.verticalBar = $('<div class="z-scroll-vertical-bar"><a href="javascript:void(0);"></a></div>');
	    this.verticalBlock = this.verticalBar.children('a');

	    this.target.wrapInner($('<div class="z-scroll-container" style="position:absolut;"></div>'));
	    this.container = this.target.find('.z-scroll-container:eq(0)');
	    this.target.append(this.verticalBar);
	    this.target.css('overflow','hidden');
	    this.target.css('padding-right','12px');
	    this.target.addClass('z-scroll-box');

	    this.init();
	    this.bindEvent();
	},
	init: function(o){
	    if(o != undefined){
		this.targetWidth  = o.targetWidth;
		this.height = o.height;
		this.position.top = 0;
		this.scroll();
	    }

	    if(this.targetHeight <= this.height){
		this.verticalBar.hide();
	    }else{
		this.verticalBar.show();
		this.verticalBlock.height(this.verticalBlockHeight);
	    }

	    this.container.width(this.targetWidth-20);
	    this.target.height(this.height);
	},
	bindEvent : function(){
	    var _this = this,
	    startMove = false;
	    //监听鼠标滚动事件
	    if($.browser.mozilla){
		document.addEventListener('DOMMouseScroll',function(event){
		    _this.onMouseWheel(_this,event);
		},true);
	    }else{
		$(this.target).bind('mousewheel',function(event){
		    _this.onMouseWheel(_this,event);
		});
	    }

	    //监听滑块移动事件
	    $(this.target.find('.z-scroll-vertical-bar a')).mousedown(function(){
		return !(startMove = true);
	    });
	    $(document).mousemove(function(event){
		if(startMove){
		    _this.position.top = event.pageY-_this.target.offset().top-_this.verticalBlockHeight/2;

		    if(_this.position.top > _this.height-_this.verticalBlockHeight){
			_this.position.top = _this.height-_this.verticalBlockHeight;
		    }

		    if(_this.position.top < 0){
			_this.position.top = 0;
		    }

		    _this.scroll();
		}
		return false;
	    });
	    $(document).mouseup(function(){
		return startMove = false;
	    });

	    $(this.verticalBar).click(function(event){
		_this.position.top = event.pageY-_this.target.offset().top-_this.verticalBlockHeight/2;

		if(_this.position.top > _this.height-_this.verticalBlockHeight){
		    _this.position.top = _this.height-_this.verticalBlockHeight;
		}

		if(_this.position.top < 0){
		    _this.position.top = 0;
		}

		_this.scroll(1);
	    });
	},
	onMouseWheel : function(_this,event){
	    if(_this.container.height() > _this.height){
		var direction = $.browser.mozilla?-event.detail:event.originalEvent.wheelDelta,
		step= 20 * (_this.height-_this.verticalBlockHeight)/(_this.container.height() - _this.height);

		if(direction == -Math.abs(direction)){
		    //向下滚动
		    if(_this.position.top < (_this.height-_this.verticalBlockHeight)){
			var lastDistance = _this.height-_this.verticalBlockHeight-_this.position.top;
			_this.position.top += lastDistance<step?lastDistance:step;
		    }
		}else{
		    //向上滚动
		    if(_this.position.top > 0){
			_this.position.top -= _this.position.top<step?_this.position.top:step;
		    }
		}
		_this.scroll();
	    }
	},
	scroll : function(animate){
	    if(this.container.height() > this.height){
		if(this.position.top <0){
		    this.position.top = 0;
		}

		if(this.position.top > (this.height-this.verticalBlockHeight)){
		    this.position.top = this.height-this.verticalBlockHeight;
		}

		$(this.verticalBlock).show().css('top',this.position.top+'px');

		var l = -(this.position.top/(this.height-this.verticalBlockHeight))*(this.container.height()-this.height)+'px';
		if(animate||false){
		    this.target.find('.z-scroll-container').animate({
			'top':l
		    }, 300);
		}else{
		    this.target.find('.z-scroll-container').css('top',l);
		}
	    }
	}
    };

    Z.tab = function(tabBtns,tabPans,classes,onTab){
	classes  = classes || ["",""];
	onTab = onTab || function(){};

	function show(i){
	    $(tabBtns).removeClass(classes[0]).eq(i).addClass(classes[0]).show();
	    $(tabPans).removeClass(classes[1]).hide().eq(i).addClass(classes[1]).show();
	}

	show(0);

	$(tabBtns).each(function(i){
	    $(this).click(function(){
		show(i);
		onTab(i);
		return false;
	    });
	});
    };


    /* start slide show */
    Z.SlideShow = function(target,width,height,thumbWidth,thumbHeight){
	var _this = this;

	this.page = 0;
	this.index = 0;

	this.count = $(target).find('.z-thumbnail-container td a').length;
	this.pictureContainer = $(target).find('.z-large-picture-container');
	this.picture = $(target).find('.z-large-picture-container img.z-large-picture');
	this.thumbnailContainer = $(target).find('.z-thumbnail-container');
	this.thumbnailTable = $(target).find('.z-thumbnail-container table');

	Z.alignImage($(target).find('td img'),thumbWidth,thumbHeight);
	Z.alignImage($(this.picture),width,height);

	$(target).find('.z-next-page-button').click(function(){
	    _this.nextPage();
	});

	$(target).find('.z-previous-page-button').click(function(){
	    _this.previousPage();
	});


	$(target).find('.z-next-button').click(function(){
	    _this.next();
	});

	$(target).find('.z-previous-button').click(function(){
	    _this.previous();
	});

	$(target).find('.z-thumbnail-container td a').each(function(i){
	    $(this).click(function(){
		_this.index = i;
		_this.go(_this.index)
	    });
	});

	this.go(this.index);
    };


    Z.SlideShow.prototype = {
	go: function(i){
	    var src = $(this.thumbnailTable).find('td a').eq(i).find('img').attr('src'),
	    _this=this;

	    $(this.pictureContainer).find('.z-loading').show();
	    $(this.picture).attr('onabort="this.src=this.src;"');//兼容ie6
	    $(this.picture).attr('src',src.replace('_thumb.','.')).load(function(){
		$(_this.pictureContainer).find('.z-loading').fadeOut(300);
	    });
	},
	next: function(){
	    if(this.index < this.count){
		this.go(++this.index);
	    }
	},
	previous: function(){
	    if(this.index > 0){
		this.go(--this.index);
	    }
	},
	nextPage: function(){
	    var tableLeft = Math.abs(Z.parseFloat($(this.thumbnailTable).css('margin-left'))),
	    tableWidth = $(this.thumbnailTable).width(),
	    containerWidth = $(this.thumbnailContainer).width(),
	    rightHiddenLength = tableWidth - tableLeft - containerWidth;
	    if(tableWidth > containerWidth){
		$(this.thumbnailTable).animate({
		    'margin-left':  '-='+(rightHiddenLength>containerWidth?containerWidth:rightHiddenLength)+'px'
		}, 300);
	    }
	},
	previousPage : function(){
	    var tableLeft = Math.abs(Z.parseFloat($(this.thumbnailTable).css('margin-left'))),
	    containerWidth = $(this.thumbnailContainer).width();

	    $(this.thumbnailTable).animate({
		'margin-left':  '+='+(tableLeft>containerWidth?containerWidth:tableLeft)+'px'
	    }, 300);
	}
    };
    // end slide show

    // start circulate show
    /*
	{
		target
		width
		height
	}
	*/
    Z.CirculateShow = function(target,width,height){
	var self = this;
	this.index = 0;
	this.buttons = $(target).find('ul.z-button li a');
	this.imageContainer = $(target).find('.z-image-container');
	this.interval = null;
	this.target = target;
	this.width = width;
	this.height = height;

	Z.alignImage($(this.imageContainer).find('img'),width,height);

	$(this.buttons).each(function(i){
	    $(this).click(function(){
		self.index = i;
		self.go(self.tick);
		return false;
	    });
	});
	
	$(this.buttons).eq(0).trigger('click');
    };

    Z.CirculateShow.prototype = {
	go : function(f){
	    var src = $(this.buttons).eq(this.index).attr('href');
	    var loading = Z.loading(this.target);
	    var self = this;
	    
	    $(this.imageContainer).find('img').attr('src',src).removeAttr('style').load(function(){
		loading.hide();
		window.alignImage($(this),self.width,self.height);
		(f || function(){}).apply(self);
	    });

	},
	tick: function(){
	    var length = this.buttons.length,
		self=this;
		
	    if(length > 1){
		window.clearInterval(this.interval);
		this.interval = window.setInterval(function(){
		    self.index++;
		    if(self.index == length){
			self.index=0;
		    }
		    self.go();
		},5000);
	    }
	}
    };
    // end circulate show

    Z.substr = function(str,start,length,subfix){
	//str.replace(/(.{10}).*/g,'$1'+(str[11]!==undefined?'...':''));
	var s = str.substr(start,length);
	if(str.length > length){
	    s += subfix||'...';
	}
	return s;
    };

    Z.trimHtmpTags = function(html){
	return (html||'').replace(/(?:<[^<]+>|(?:&nbsp){2,}|\s+)/g,'');
    };

    Z.log = function(){
	if(typeof console != 'undefined'){
	    console.log(arguments);
	}
    };

    Z.fillForm = function(form,data){
	$(form).find("input").each(function(){
	    var name = $(this).attr("name");
	    switch($(this).attr("type")){
		case "radio":
		    if($(this).val()==data[name]){
			$(this).attr("checked","checked");
		    }
		    break;
		case "checkbox":
		    if(data[name].search($(this).val())!=-1){
			$(this).attr("checked","checked");
		    }
		    break;
		case "text":
		case "hidden":
		    $(this).val(data[name]);
		    break;
	    }
	});

	$(form).find("select,textarea").each(function(){
	    $(this).val(data[$(this).attr("name")]);
	});
    };

    Z.cleanForm = function(form){
	$(form).find("input").each(function(){
	    switch($(this).attr("type")){
		case "radio":
		case "checkbox":
		    $(this).removeAttr("checked");
		    break;
		case "text":
		case 'hidden':
		    $(this).val("");
		    break;
	    }
	});

	$(form).find("textarea").each(function(){
	    $(this).val("");
	});

	$(form).find("select").each(function(){
	    $(this).val(0);
	});
    };

    Z.parseFloat = function(num,fixed){
	return parseFloat(num==""?0:num).toFixed(fixed||2);
    };

    Z.parseInt = function(num){
	return parseInt(num==""?0:num);
    };

    Z.url = function(url){
	if(/^\/assets/.test(url)){
	    return SITE_URL+url;
	}else{
	    return SITE_URL+'/index.php'+url;
	}
    };

    Z.innerTip = function(element,string){
	$(element).val(string).focus(function(){
	    if($(this).val() == string){
		$(this).addClass('active').val('');
	    }
	}).blur(function(){
	    if($(this).val() == ''){
		$(this).removeClass('active').val(string);
	    }else if($(this).val() == string){
		$(this).removeClass('active');
	    }
	});
    };

    Z.alignImage = function(images,width,height){
	$(images).each(function(){
	    $(this).load(function(){
		if(width == 0){
		    $(this).height(height);
		}else if(height == 0){
		    $(this).width(width);
		}else{
		    var h = $(this).height(),w = $(this).width();
		    if(h/w >= height/width){
			if(h > height){
			    w = Z.parseFloat(height / h * w);
			    $(this).height(height);
			    $(this).css('margin-left',(width-w)/2+'px');
			}else{
			    $(this).css('margin-left',(width-w)/2+'px');
			    $(this).css('margin-top',(height-h)/2+'px');
			}
		    }else{
			if(w > width){
			    h = Z.parseFloat(width / w * h);
			    $(this).width(width);
			    $(this).css('margin-top',(height-h)/2+'px');
			}else{
			    $(this).css('margin-left',(width-w)/2+'px');
			    $(this).css('margin-top',(height-h)/2+'px');
			}
		    }
		}
	    });
	});
    };

    Z.breakText = function(target,length){
	$(target).each(function(){
	    var oldText = $(this).html().replace(/&nbsp;/g,' '),
	    newText = [],
	    times,
	    l = oldText.length;

	    if(l > length){
		times = Math.ceil(l/length);
		for(var i=0;i<=times;i++){
		    newText.push(oldText.substr(i*length, length));
		}
		$(this).html(newText.join('<br/>'));
	    }
	});
    };

    Z.moveScroll = function(t){
	var pt = $(t).offset().top,
	h = $(t).height(),
	ih = $(t).children().eq(0).outerHeight() || 0;
	$(t).children().eq(0).css('position','absolute');
	if(ih > h){
	    $(t).mousemove(function(e){
		$(this).children().eq(0).css('top',-Math.ceil((e.pageY-pt)/h*(ih-h+20))+'px');
	    });
	}
    };

    window.Z = Z;

    String.prototype.trim = function(){
	return this.replace(/(:?^\s*|\s*$)/g,'');
    };

    window.alignImage = function(image,width,height){
	var w = width ,h = height,tdw = width;
	if(width == 0){
	    $(image).height(height);
	    tdw = $(image).width() * height / $(image).height();
	}else if(height == 0){
	    $(image).width(width);
	}else{
	    h = $(image).height();
	    w = $(image).width();
	    if(h/w >= height/width){
		if(h > height){
		    w = Z.parseFloat(height / h * w);
		    tdw = w;
		    $(image).height(height);
		    $(image).css('margin-left',(width-w)/2+'px');
		}else{
		    $(image).css('margin-left',(width-w)/2+'px');
		    $(image).css('margin-top',(height-h)/2+'px');
		}
	    }else{
		if(w > width){
		    h = Z.parseFloat(width / w * h);
		    tdw = $(image).width() * h / $(image).height();
		    $(image).width(width);
		    $(image).css('margin-top',(height-h)/2+'px');
		}else{
		    $(image).css('margin-left',(width-w)/2+'px');
		    $(image).css('margin-top',(height-h)/2+'px');
		}
	    }
	}
	
	if($.browser.msie){
	    var td = $(image).parent().parent('td');
	    if(td.length > 0){
		$(td).width(tdw)
	    }
	}
    };
})(window);